﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowUtil;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.Configuration;
using System.Text;
using System.Net.Mail;

namespace CustomSignature.Layouts.CustomSignature
{
    public partial class DocumentValidationUtility : LayoutsPageBase
    {
        #region Get values from Web.config
        string siteURL = ConfigurationSettings.AppSettings["SiteURL"];
        string listSingleDocumentLibrary = ConfigurationSettings.AppSettings["SingleSignDocumentLibrary"];
        string listSingleWorkFlowHistory = ConfigurationSettings.AppSettings["SingleSignWorkflowHistory"];
        string singleDocumentLibraryURL = ConfigurationSettings.AppSettings["SingleSignDocumentLibraryURL"];

        string listMultipleDocumentLibrary = ConfigurationSettings.AppSettings["MultipleSignDocumentLibrary"];
        string listMultipleWorkFlowHistory = ConfigurationSettings.AppSettings["MultipleSignWorkflowHistory"];
        string multipleDocumentLibraryURL = ConfigurationSettings.AppSettings["MultipleSignDocumentLibraryURL"];
        string documentNotAvailable = ConfigurationSettings.AppSettings["DocumentNotAvailable"];
        #endregion

        #region Properties for single and multiple signature
        public string UserName { get; set; }
        public string DocumentID { get; set; }
        public string DocumentName { get; set; }

        public string PurposeofSigning { get; set; }
        public string FileLeafRef { get; set; }
        public string DateSigned { get; set; }

        public string Signers { get; set; }
        public string DocumentStatus { get; set; }
        public string ListWorkflowHistory { get; set; }

        public string ListDocumentLibrary { get; set; }
        public bool IsSingle { get; set; }

        public string UserNameSignerOne { get; set; }
        public string PurposeOfSignatureSignerOne { get; set; }
        public string DocumentStatusSignerOne { get; set; }

        public string DateSignedSignerOne { get; set; }
        public string UserNameSignerTwo { get; set; }
        public string PurposeOfSignatureSignerTwo { get; set; }

        public string DocumentStatusSignerTwo { get; set; }
        public string DateSignedSignerTwo { get; set; }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(siteURL);
        }

        protected void btnValidate_Click(object sender, EventArgs e)
        {
            IsSingle = true;
            ListDocumentLibrary = listSingleDocumentLibrary;
            ListWorkflowHistory = listSingleWorkFlowHistory;
            ValidateDocuments();
            IsSingle = false;
            ListDocumentLibrary = listMultipleDocumentLibrary;
            ListWorkflowHistory = listMultipleWorkFlowHistory;
            ValidateDocuments();
        }

        private void ValidateDocuments()
        {
            string approvedEncryptedValue = string.Empty;
            string currentEncryptedValue = string.Empty;
            using (SPSite spSite = new SPSite(siteURL))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    SPQuery spQuery = new SPQuery();
                    //string listQuery = string.Format("<Where><Eq><FieldRef Name=\"_ModerationStatus\" /><Value Type=\"ModStat\">{0}</Value></Eq></Where>", "Approved");
                    string listQuery = string.Format("<Where><Eq><FieldRef Name=\"DocumentValidity\" /><Value Type=\"Text\">{0}</Value></Eq></Where>", "Valid");
                    lblMessage.Text = "";
                    SPList spList = spWeb.Lists[ListDocumentLibrary];
                    spQuery.Query = listQuery;
                    SPListItemCollection spListItems = spList.GetItems(spQuery);

                    DataTable dt = spList.GetItems(spQuery).GetDataTable();

                    foreach (SPListItem item in spListItems)
                    {

                        approvedEncryptedValue = ((item["EncryptedValue"] == System.DBNull.Value) ? "" : item["EncryptedValue"].ToString().Trim());
                        if (IsSingle)
                        {
                            UserName = item["UserName"].ToString().Trim();
                            DocumentID = item["ID"].ToString();
                            DocumentName = item["FileLeafRef"].ToString().Trim();
                            PurposeofSigning = item["PurposeOfSignature"].ToString().Trim();
                            FileLeafRef = item["FileLeafRef"].ToString().Trim();
                            DateSigned = item["DateSigned"].ToString().Trim();
                            Signers = item["Signers"].ToString().Trim();
                            DocumentStatus = item["DocumentStatus"].ToString().Trim();

                            currentEncryptedValue = EncryptStringValue(
                                                          item["UserName"].ToString().Trim() +
                                                          item["PurposeOfSignature"].ToString().Trim() +
                                                          item["FileLeafRef"].ToString().Trim() +
                                                          item["DateSigned"].ToString().Trim() +
                                                          item["Signers"].ToString().Trim() +
                                                          item["DocumentStatus"].ToString().Trim()).ToString().Trim();
                        }
                        else
                        {
                            UserNameSignerOne = item["UserNameSignerOne"].ToString().Trim();
                            PurposeOfSignatureSignerOne = item["PurposeOfSignatureSignerOne"].ToString().Trim();
                            DocumentStatusSignerOne = item["DocumentStatusSignerOne"].ToString().Trim();
                            DateSignedSignerOne = item["DateSignedSignerOne"].ToString().Trim();

                            UserNameSignerTwo = item["UserNameSignerTwo"].ToString().Trim();
                            PurposeOfSignatureSignerTwo = item["PurposeOfSignatureSignerTwo"].ToString().Trim();
                            DocumentStatusSignerTwo = item["DocumentStatusSignerTwo"].ToString().Trim();
                            DateSignedSignerTwo = item["DateSignedSignerTwo"].ToString().Trim();

                            currentEncryptedValue = EncryptStringValue(
                                                        item["UserNameSignerOne"].ToString().Trim() +
                                                        item["PurposeOfSignatureSignerOne"].ToString().Trim() +
                                                        item["DocumentStatusSignerOne"].ToString().Trim() +
                                                        item["DateSignedSignerOne"].ToString().Trim() +
                                                        item["UserNameSignerTwo"].ToString().Trim() +
                                                        item["PurposeOfSignatureSignerTwo"].ToString().Trim() +
                                                        item["DocumentStatusSignerTwo"].ToString().Trim() +
                                                        item["DateSignedSignerTwo"].ToString().Trim());

                        }
                        if (approvedEncryptedValue != currentEncryptedValue)
                        {
                            if (IsSingle)
                            {
                                item["UserName"] = UserName;
                                item["PurposeOfSignature"] = PurposeofSigning;
                                item["FileLeafRef"] = FileLeafRef;
                                item["DateSigned"] = DateSigned;
                                item["Signers"] = Signers;
                                item["DocumentStatus"] = DocumentStatus;
                                item["DocumentValidity"] = "InValid";

                                spWeb.AllowUnsafeUpdates = true;
                                item.Update();
                                spWeb.AllowUnsafeUpdates = false;
                            }
                            else
                            {

                                item["UserNameSignerOne"] = UserNameSignerOne;
                                item["PurposeOfSignatureSignerOne"] = PurposeOfSignatureSignerOne;
                                item["DocumentStatusSignerOne"] = DocumentStatusSignerOne;
                                item["DateSignedSignerOne"] = DateSignedSignerOne;
                                item["UserNameSignerTwo"] = UserNameSignerTwo;
                                item["PurposeOfSignatureSignerTwo"] = PurposeOfSignatureSignerTwo;
                                item["DocumentStatusSignerTwo"] = DocumentStatusSignerTwo;
                                item["DateSignedSignerTwo"] = DateSignedSignerTwo;

                                spWeb.AllowUnsafeUpdates = true;
                                item.Update();
                                spWeb.AllowUnsafeUpdates = false;

                            }
                            CreateWorkflowHistory();
                        }
                    }
                    lblMessage.Text = "Documents validated successfully.";
                }
            }
        }

        /// <summary>
        /// Method to encypt a string value
        /// </summary>
        /// <param name="sData"></param>
        /// <returns></returns>
        protected string EncryptStringValue(string sData)
        {
            try
            {
                byte[] encData_byte = new byte[sData.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;

            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }

        /// <summary>
        /// Method to add workflow history
        /// </summary>
        /// <param name="status"></param>
        /// <returns>bool return true if updated</returns>
        protected void CreateWorkflowHistory()
        {
            try
            {
                using (SPSite spSite = new SPSite(siteURL))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        SPList spListAddWorkflow = spWeb.Lists[ListWorkflowHistory];
                        SPListItem newHistory = spListAddWorkflow.Items.Add();

                        newHistory["Title"] = DocumentID + " - " + DateTime.Now.ToString();
                        newHistory["FileName"] = DocumentName;
                        newHistory["DateOccurred"] = DateTime.Now.ToString();
                        newHistory["EventType"] = "Warning";
                        newHistory["Description"] = "SharePoint record, signature block corrupted.";
                        newHistory.Update();
                        spWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error: " + ex.Message;
            }
        }

        /// <summary>
        /// Method to send mail
        /// </summary>
        /// <param name="status"></param>
        protected void SendMail()
        {
            string emailAddressTo = string.Empty;
            string emailAddressFrom = string.Empty;
            StringBuilder messageText = new StringBuilder();
            MailMessage mailMessage = new MailMessage();
            messageText.Append("Document hacked, signature block corrupted;<br><br>");
            emailAddressTo = "ssundararajan@consultparagon.com";
            emailAddressFrom = "pmodumudi@consultparagon.com";
            if (emailAddressTo.Length != 0)
            {
                mailMessage.To.Add(emailAddressTo);
            }

            if (emailAddressFrom.Length != 0)
            {
                mailMessage.From = new MailAddress(emailAddressFrom);
            }
            mailMessage.Subject = "Document hacked";
            mailMessage.Body = messageText.ToString();
            mailMessage.IsBodyHtml = true;
            SmtpClient smtpClient = new SmtpClient("XMAIL", 25);
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
            smtpClient.Send(mailMessage);

        }
    }
}
